using System;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using ETL.Business.Handlers.ProjectActualResourceHandler;
using ETL.Business.Handlers.ProjectHandlers;
using ETL.Business.Handlers.ProjectTaskHandler;
using ETL.Business.Handlers.ProjectUserHandler;
using ETL.Business.Helpers;
using ETL.Business.Models;
using ETL.Common;
using ETL.Common.Logging;
using ETL.Web.CustomCredential;
using ETL.Web.Filters;
using ETL.Web.Models;
using WebMatrix.WebData;

namespace ETL.Web.Controllers
{
    [Authorize]
    [InitializeSimpleMembership]
    public class EnTimeLogController : Controller
    {
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [Authorize]
        public ActionResult Index()
        {
            // check authenticated
            if (!WebSecurity.IsAuthenticated) return RedirectToAction("Login", "Account");

            // Program Initialize
            (new ProgramInitialize()).Execute(ETLCredential.UserId, ETLCredential.UserFullName);

            // prepare date of viewmodel
            var dashboardViewModel = new DashboardViewModel();

            #region Check user role for projects loading

            // Get all projects of this user, including selected project if it's existing
            List<ProjectModel> allProjectsOfThisUser = (new GetProjects()).ExecuteToList(ETLCredential.UserId);

            // Bind to viewmodel
            dashboardViewModel.ProjectModels = allProjectsOfThisUser;

            // Check roles of user
            if (Roles.IsUserInRole(Constants.RoleName.Lead))
            {
                ViewBag.IsLeadRole = true;
            }

            #endregion

            #region Check user role for other engineer dropdownlist

            // Admin roles only
            if (Roles.IsUserInRole(ETLCredential.UserId, Constants.RoleName.Admin))
            {
                dashboardViewModel.ProjectUserModels = (new GetAllUsers()).Execute();
                ViewBag.IsAdminRole = true;
            }

            #endregion

            // Get alert interval if user not log on to a task
            string alertInterval = ConfigurationManager.AppSettings["AlertInterval"];
            ViewBag.AlertInterval = alertInterval;


            return View(dashboardViewModel);
        }

        #region Logon to task

        /// <summary>
        /// Activity of logon to a specific task, with task id
        /// </summary>
        /// <param name="taskId"></param>
        /// <returns></returns>
        public string LogOnToATask(decimal taskId)
        {
            // check authenticated status
            if (!WebSecurity.IsAuthenticated) return string.Empty;

            ProjectTaskModel currentTask = (new GetProjectTask()).Execute(taskId);
            decimal genTaskId = currentTask.ProjectTasks.GEN_TASK_ID;
            decimal genProjectId = 0;
            if (currentTask.ProjectTasks.GEN_PROJECT_ID != null)
            {
                genProjectId = currentTask.ProjectTasks.GEN_PROJECT_ID.Value;
            }

            // log on to task
            string result = (new LogOnToTask()).Execute(genProjectId, genTaskId, ETLCredential.UserId,
                                                        ETLCredential.UserFullName);

            return result;
        }

        #endregion

        #region Log on to last task

        /// <summary>
        /// Logon to last task
        /// </summary>
        /// <returns></returns>
        public string LogOnToLastTask()
        {
            // check authenticated
            if (!WebSecurity.IsAuthenticated) return string.Empty;

            ProjectActualResourceUsageModel lastActualResourceUsages =
                (new GetLastActualResourceUsage().Execute(ETLCredential.UserId));

            if (lastActualResourceUsages.ActualResourceUsage != null)
            {
                decimal? tmpTask = lastActualResourceUsages.ActualResourceUsage.GEN_TASK_ID;
                decimal genTaskId = tmpTask == null ? 0 : tmpTask.Value;
                decimal? tmpPrj = lastActualResourceUsages.ActualResourceUsage.TASK.GEN_PROJECT_ID;
                decimal genProjectId = tmpPrj == null ? 0 : tmpPrj.Value;

                // log on to task
                string result = (new LogOnToTask()).Execute(genProjectId, genTaskId, ETLCredential.UserId,
                                                            ETLCredential.UserFullName);

                return result;
            }
            else
            {
                return null;
            }
        }

        public ActionResult GetLastTask()
        {
            // check authenticated status
            if (!WebSecurity.IsAuthenticated) return null;

            ProjectActualResourceUsageModel lastActualResourceUsages =
                (new GetLastActualResourceUsage().Execute(ETLCredential.UserId));

            IEnumerable<ProjectTaskModel> taskList = null;
            string message = "none";
            if (lastActualResourceUsages.ActualResourceUsage != null)
            {
                if (lastActualResourceUsages.ActualResourceUsage.TASK.GEN_PROJECT_ID != null)
                {
                    decimal projectId = lastActualResourceUsages.ActualResourceUsage.TASK.PROJECT.PROJECT_ID;
                    taskList = (new GetProjectTasks()).Execute(projectId, ETLCredential.UserId);
                }
            }
            if (taskList != null)
            {
                return PartialView("_TaskGridPartial", taskList);
            }
            else
            {
                return null;
            }
        }

        public ActionResult GetLastProject()
        {
            // check authenticated status
            if (!WebSecurity.IsAuthenticated) return null;

            ProjectActualResourceUsageModel lastActualResourceUsages =
                (new GetLastActualResourceUsage().Execute(ETLCredential.UserId));
            if (lastActualResourceUsages.ActualResourceUsage != null)
            {
                decimal projectId = lastActualResourceUsages.ActualResourceUsage.TASK.PROJECT.PROJECT_ID;
                var allProjects = (new GetProjects()).ExecuteToList(ETLCredential.UserId, projectId);

                return PartialView("_ProjectDropDownListPartial", allProjects.AsEnumerable());
               
            }
            else
            {
                return null;
            }
            return null;
        }

        public ActionResult GetLastActualResourceUsages()
        {
            // check authenticated status
            if (!WebSecurity.IsAuthenticated) return null;

            ProjectActualResourceUsageModel lastActualResourceUsages =
                (new GetLastActualResourceUsage().Execute(ETLCredential.UserId));
            if (lastActualResourceUsages.ActualResourceUsage != null)
            {
                if (lastActualResourceUsages.ActualResourceUsage.TASK.TASK_ID != null)
                {
                    decimal taskId = lastActualResourceUsages.ActualResourceUsage.TASK.TASK_ID.Value;
                    return GetActualResourceOfTask(taskId);
                }
            }
            else
            {
                return null;
            }
            return null;
        }

        public string GetLastProjectDetail()
        {
            // check authenticated status
            if (!WebSecurity.IsAuthenticated) return null;

            ProjectActualResourceUsageModel lastActualResourceUsages =
                (new GetLastActualResourceUsage().Execute(ETLCredential.UserId));
            string message = "none";
            if (lastActualResourceUsages.ActualResourceUsage != null)
            {
                decimal projectId = lastActualResourceUsages.ActualResourceUsage.TASK.PROJECT.PROJECT_ID;
                return GetProjectDetail(int.Parse(projectId.ToString()));
            }
            else
            {
                return string.Empty;
            }
        }

        #endregion

        #region Get tasks, project detailed by project

        /// <summary>
        /// Return a partial view of task grid
        /// </summary>
        /// <param name="projectId"></param>
        /// <returns></returns>
        public ActionResult GetTask(decimal projectId)
        {
            // check authenticated status
            if (!WebSecurity.IsAuthenticated) return null;


            if (projectId > 0)
            {
                IEnumerable<ProjectTaskModel> taskList = (new GetProjectTasks()).Execute(projectId,
                                                                                              ETLCredential.UserId);
                return PartialView("_TaskGridPartial", taskList);
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// function to get project detailed content
        /// </summary>
        /// <param name="projectId"></param>
        /// <returns></returns>
        public string GetProjectDetail(int projectId)
        {
            // check authenticated
            if (!WebSecurity.IsAuthenticated) return string.Empty;

            ProjectModel currentProject = (new GetProject()).Execute(projectId);

            string result = string.Empty;
            if (currentProject != null)
            {
                result += currentProject.ProjectLeadEngineer + "#";
                result += String.Format("{0:MMM/dd/yyyy}", currentProject.ProjectStartDate) + "#";
                result += String.Format("{0:MMM/M/yyyy}", currentProject.ProjectEndDate) + "#";
                result += currentProject.ProjectStatus + "#";
            }
            return result;
        }

        /// <summary>
        /// Return a partial view of task grid
        /// </summary>
        /// <param name="taskId"></param>
        /// <returns></returns>
        public ActionResult GetActualResourceOfTask(decimal taskId)
        {
            // check authenticated status
            if (!WebSecurity.IsAuthenticated) return null;

            // convert to short
            ProjectTaskModel currentTask = (new GetProjectTask()).Execute(taskId);

            decimal projectId = currentTask.ProjectId;

            IEnumerable<ProjectActualResourceUsageModel> result = (new GetActualResourceUsage()).Execute(projectId,
                                                                                                         taskId);

            if (result != null)
            {
                return PartialView("_ActualResourcePartial", result.OrderByDescending(s => s.StartDate));
            }
            else
            {
                return PartialView("_ActualResourcePartial", null);
            }
        }

        #endregion

        #region ETL Actual Resource Usages

        public string CheckLastActualResourceUsage()
        {
            ProjectActualResourceUsageModel lastActualResourceUsages = 
                (new GetLastActualResourceUsage().Execute(ETLCredential.UserId));
            string message = "none";
            if(lastActualResourceUsages == null)
            {
                message = "null";
                return message;
            }

            
            if (string.IsNullOrEmpty(lastActualResourceUsages.ClockOffBy))
            {
                if (lastActualResourceUsages.EndDate == null)
                {
                    message = "WalkedOff";
                }
                else
                {
                    message = "SwipedOut";
                }
            }


            return message;
            //if (lastActualResourceUsages.ActualResourceUsage !=null && lastActualResourceUsages.EndDate != null && string.IsNullOrEmpty(lastActualResourceUsages.ClockOffBy))
            /*if (lastActualResourceUsages.ActualResourceUsage != null && string.IsNullOrEmpty(lastActualResourceUsages.ClockOffBy))
            {
               

                if (lastActualResourceUsages.EndDate == null)
                {
                    message =
                    "You walked off site forgetting to clock off your most recent task: \n" +
                    "Here are the details of your most recent task : \n" +
                    "Project : " + lastActualResourceUsages.ActualResourceUsage.RESOURCE_INSTANCES.PROJECT_NAME + "\n" +
                    "User : " + lastActualResourceUsages.ActualResourceUsage.RESOURCE_INSTANCES.RESOURCE_NAME + "\n" +
                    "Start date : " + lastActualResourceUsages.StartDate + "\n" +
                    "End date : " + "Not Entered\n\n\n" +
                    "Would you like to enter your end time manually ?";
                }
                else if (string.IsNullOrEmpty(lastActualResourceUsages.ClockOffBy))
                {
                    message =
                    "You walked off site without signing out: \n" +
                    "Here are the details of your most recent task for review : \n" +
                    "Project : " + lastActualResourceUsages.ActualResourceUsage.RESOURCE_INSTANCES.PROJECT_NAME + "\n" +
                    "User : " + lastActualResourceUsages.ActualResourceUsage.RESOURCE_INSTANCES.RESOURCE_NAME + "\n" +
                    "Start date : " + lastActualResourceUsages.StartDate + "\n" +
                    "End date : " + lastActualResourceUsages.EndDate + "\n" +
                    "Would you like to adjust your end time manually ?";
                }
                return message;
            }
            else if (string.IsNullOrEmpty(lastActualResourceUsages.ClockOffBy)) 
            {
                return message;
            
            }
            else if (lastActualResourceUsages.ActualResourceUsage != null)
            {
                return string.Empty;
            }
            else
            {
                return "ok";
            }*/
        }

        public ActionResult GetWalkedOffDialog()
        {
            try
            {
                ProjectActualResourceUsageModel lastActualResourceUsages =
                    (new GetLastActualResourceUsage().Execute(ETLCredential.UserId));
                return PartialView("_InformWalkedOff", lastActualResourceUsages);
            }
            catch (Exception ex)
            {
                // Logging
                LogService.Service.Error(ex.Message);
                // Redirect to 500 page
                throw new HttpException(404, "Page not found");
            }
        }

        public ActionResult GetSwipedOutButNotClockedOffDialog()
        {
            try
            {
                ProjectActualResourceUsageModel lastActualResourceUsages =
                    (new GetLastActualResourceUsage().Execute(ETLCredential.UserId));
                return PartialView("_InformSwipedOut", lastActualResourceUsages);
            }
            catch (Exception ex)
            {
                // Logging
                LogService.Service.Error(ex.Message);
                // Redirect to 500 page
                throw new HttpException(404, "Page not found");
            }
        }

        public string UpdateLastActualResourceUsage(string dateTime)
        {
            ProjectActualResourceUsageModel lastActualResourceUsages =
                (new GetLastActualResourceUsage().Execute(ETLCredential.UserId));

            string taskId = lastActualResourceUsages.ActualResourceUsage.GEN_TASK_ID.ToString();
            decimal lastGenId = lastActualResourceUsages.GenActualResourceUsageId;
            string projectId = lastActualResourceUsages
                .ActualResourceUsage
                .TASK.GEN_PROJECT_ID.ToString();
            DateTime newEndTime = DateTime.Now;
            DateTime ukDateTimeFormat = DateTime.Parse(dateTime, CultureInfo.GetCultureInfo("en-us"));
            //bool b = DateTime.TryParse(dateTime, out newEndTime);
            bool b = DateTime.TryParse(ukDateTimeFormat.ToString(), out newEndTime);
            if (b == false)
            {
                return "-1";
            }
            else
            {
                (new UpdateActualResourceUsage()).Execute(lastGenId, projectId, taskId, newEndTime, ETLCredential.UserId);
                return "1";
            }
        }

        public string EndOfDay()
        {
            ProjectActualResourceUsageModel lastActualResourceUsages =
                (new GetLastActualResourceUsage().Execute(ETLCredential.UserId));
            decimal lastGenId = lastActualResourceUsages.GenActualResourceUsageId;
            string taskId = lastActualResourceUsages.ActualResourceUsage.GEN_TASK_ID.ToString();
            string projectId = lastActualResourceUsages
                .ActualResourceUsage
                .TASK.GEN_PROJECT_ID.ToString();

            DateTime newEndTime = DateTime.Now;
            (new UpdateActualResourceUsage()).Execute(lastGenId, projectId, taskId, newEndTime, ETLCredential.UserId);
            return "1";
        }

        public ActionResult GetEnterDateDialog()
        {
            try
            {
                ProjectActualResourceUsageModel lastActualResourceUsages =
                    (new GetLastActualResourceUsage().Execute(ETLCredential.UserId));
                return PartialView("_EnterDatePartial", lastActualResourceUsages);
            }
            catch (Exception ex)
            {
                // Logging
                LogService.Service.Error(ex.Message);
                // Redirect to 500 page
                throw new HttpException(404, "Page not found");
            }
        }

        #endregion
    }
}